from rest_framework import serializers
from .models import TestReport, ReportDetail, Dashboard
import json


class TestReportSerializer(serializers.ModelSerializer):
    created_by_name = serializers.CharField(source='created_by.username', read_only=True)
    execution_data = serializers.SerializerMethodField()

    class Meta:
        model = TestReport
        fields = '__all__'
        read_only_fields = ('created_at',)

    def get_execution_data(self, obj):
        try:
            return json.loads(obj.execution_data) if obj.execution_data else {}
        except:
            return {}


class ReportDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = ReportDetail
        fields = '__all__'


class DashboardSerializer(serializers.ModelSerializer):
    class Meta:
        model = Dashboard
        fields = '__all__'


class ReportFilterSerializer(serializers.Serializer):
    report_type = serializers.CharField(required=False)
    start_date = serializers.DateField(required=False)
    end_date = serializers.DateField(required=False)
    status = serializers.CharField(required=False)


class StatisticsSerializer(serializers.Serializer):
    total_reports = serializers.IntegerField()
    total_cases = serializers.IntegerField()
    total_passed = serializers.IntegerField()
    total_failed = serializers.IntegerField()
    overall_pass_rate = serializers.FloatField()
    recent_reports = serializers.ListField()